<script>
import { getDatabases, useDatabaseTableList, useTableImportSubmitApi } from '@/api/generator'

export default {
  name: 'ImportTable',
  data() {
    return {
      dataForm: {
        id: '',
        tableNameListSelections: [],
        datasourceId: '',
        datasourceList: [],
        tableList: [],
        table: {
          tableName: ''
        },
        primaryKey: 'tableName'
      },
      visible: false
    }
  },
  created() {
    this.fetchDatabases()
  },
  methods: {
    fetchDatabases() {
      getDatabases().then(resp => {
        const { data } = resp
        this.dataForm.datasourceList = data
      })
    },
    getTableList() {
      useDatabaseTableList(this.dataForm.datasourceId).then(resp => {
        this.dataForm.tableList = resp.data
      })
    },
    submitHandle() {
      const data = this.dataForm.tableNameListSelections || []
      if (data.length === 0) {
        return this.$message.error('请选择表')
      }
      useTableImportSubmitApi(this.dataForm.datasourceId, data).then(() => {
        this.$message.success('导入成功！')
        this.visible = false
      })
    },
    selectionChangeHandle(selection) {
      this.dataForm.tableNameListSelections = selection.map((item) =>
        this.dataForm.primaryKey && item[this.dataForm.primaryKey])
    },
    open() {
      this.visible = true
    }
  }
}
</script>

<template>
  <el-dialog :visible.sync="visible" title="导入数据库表" :close-on-click-modal="false">
    <el-form ref="dataFormRef" size="small" :model="dataForm" label-width="auto">
      <el-form-item label="数据源" prop="datasourceId">
        <el-select v-model="dataForm.datasourceId" style="width: 100%" placeholder="请选择数据源" @change="getTableList">
          <el-option label="默认数据源" value="0" />
          <el-option v-for="ds in dataForm.datasourceList" :key="ds.id" :label="ds.connName" :value="ds.id" />
        </el-select>
      </el-form-item>
      <el-table size="small" :data="dataForm.tableList" border style="width: 100%" :max-height="300" @selection-change="selectionChangeHandle">
        <el-table-column type="selection" header-align="center" align="center" width="60" />
        <el-table-column prop="tableName" label="表名" header-align="center" align="center" />
        <el-table-column prop="tableComment" label="表说明" header-align="center" align="center" />
      </el-table>
    </el-form>
    <template #footer>
      <el-button size="small" @click="visible = false">取消</el-button>
      <el-button size="small" type="primary" @click="submitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>
